package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.CustomOuterInterface;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.OuterInterfaceTableFieldsEnum;
import com.py.credit.service.CustomOuterInterfaceService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping(value = "/interface")
public class CustomOuterInterfaceController {

    private final static String FRONT_TABLE_CUSTOM_INTERFACE_ID = "customInterfaceTable";

    @Autowired
    private CustomOuterInterfaceService customOuterInterfaceService;

    @Autowired
    private RemoteBaseService remoteBaseService;

    /**
     * 新增共享接口动态配置sql中的表和字段信息
     *
     * @param customOuterInterface
     * @param request
     * @return
     */
    @IgnoreAuthority
    @RequestMapping("/add.json")
    public RestServiceResult<Object> addSgs(@RequestBody CustomOuterInterface customOuterInterface, HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo && userInfo.getId() != null) {
                customOuterInterface.setUser(userInfo.getUsername());
            } else {
                ExceptionLogger.error("CustomOuterInterfaceController#add", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("CustomOuterInterfaceController#add", "未获取到当前用户信息！");
        }
        customOuterInterfaceService.addSgs(customOuterInterface);
        return new RestServiceResult<>();

    }
    
    @RequestMapping("/getDetail.json")
    public RestServiceResult<CustomOuterInterface> getDetail(
            @RequestParam(value = "id", defaultValue = "") int id) {
        CustomOuterInterface record = customOuterInterfaceService.getRecordById(id);
        return new RestServiceResult<>(record);
    }
    @IgnoreAuthority
    @RequestMapping("/edit.json")
    public RestServiceResult<Object> edit(@RequestBody CustomOuterInterface customOuterInterface, HttpServletRequest request) {
    	RestServiceResult<Object> object = new RestServiceResult<Object>();
    	try {
    	   customOuterInterfaceService.update(customOuterInterface);
    	   object.setData("修改成功");
    	  
	} catch (Exception e) {
		 object.setData("修改失败");
  	   
	}
    	 return new RestServiceResult<>(object);

    }

    @RequestMapping("/getTableList.json")
    public RestServiceResult<List<Map<String, Object>>> getList(
            @RequestParam(value = "condition", defaultValue = "") String condition, Page page,
            HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String[] configColumns = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_CUSTOM_INTERFACE_ID);
            } else {
                ExceptionLogger.error("CustomOuterInterfaceController#getTableList", "未获取到当前用户信息！");
            }
        } else {

            ExceptionLogger.error("CustomOuterInterfaceController#getTableList", "未获取到当前用户信息！");
        }

        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? OuterInterfaceTableFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);

        String[] additionalColumns = {"id","tablename"};

        List<Map<String, Object>> tableList = customOuterInterfaceService.getByConditionForPage(showColumns,
                additionalColumns, condition, page);

        return new RestServiceResult<>(page.getTotalCount(), tableList);

    }

    @RequestMapping(value = "/addColunms.json")
    public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns") String[] columns,
                                                    HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_CUSTOM_INTERFACE_ID, columns);
            } else {
                ExceptionLogger.error("CustomOuterInterfaceController#addShowColunms", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("CustomOuterInterfaceController#addShowColunms", "未获取到当前用户信息！");
        }
        return new RestServiceResult<>();
    }

    @RequestMapping(value = "/getOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getCommonContentOptionalColums() {
        return new RestServiceResult<>(OuterInterfaceTableFieldsEnum.getOptionalColumns());

    }

    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getCommonContentAdvancedConditionColumns() {
        return new RestServiceResult<>(OuterInterfaceTableFieldsEnum.getAdvancedConditionColumns());
    }

    @RequestMapping(value = "/export.json")
    public void export(@RequestParam(value = "condition", defaultValue = "") String condition,
                       @RequestParam(value = "columnEN", defaultValue = "") String columnEN, Page page,
                       HttpServletResponse response) throws IOException {
        page.setLimit(1000);
        List<String> columns = JSONArray.parseArray(columnEN, String.class);
        List<Map<String, Object>> data = customOuterInterfaceService.getByConditionForPage(columns, null, condition,
                page);
        List<OptionalColumn> optionalColumns = OuterInterfaceTableFieldsEnum.getOptionalColumns();
        ExcelUtil.downloadExcel(response, data, "接口管理列表", "接口管理列表", columns, optionalColumns);
    }

    /**
     * 功能描述: 前台网站列表数据通用接口
     *
     * @param interfaceCode 接口code
     * @param condition     参数信息
     * @return 查询结果
     * @author YaoS
     * @date 2020/4/23 20:00
     */
 
    @RequestMapping(value = "/list/getResult.do")
    public RestServiceResult<List<Map<String, Object>>> getListResult(
            @RequestParam(value = "interfaceCode", defaultValue = "") String interfaceCode,
            @RequestParam(value = "condition", defaultValue = "") String condition) {
        if (StringUtils.isBlank(interfaceCode)) {
            throw new ServiceException("参数[interfaceCode]缺失");
        }
        CustomOuterInterface record = customOuterInterfaceService.getRecordByCode(interfaceCode);
        if (record != null && StringUtils.isNotBlank(record.getListSql())) {
        	
        		 List<Map<String, Object>> resultList = customOuterInterfaceService.execute(condition, record.getListSql(),record.getName());
                 Integer pageCount = customOuterInterfaceService.executeCount(condition, record.getListSql());
                 return new RestServiceResult<>(pageCount, resultList);

        	
            
        } else {
            throw new ServiceException("获取接口配置数据异常,请检查接口配置,id===》[" + interfaceCode + "]");
        }

    }

    @RequestMapping(value = "/detail/getResult.do")
    public RestServiceResult<List<Map<String, Object>>> getDetailResult(
            @RequestParam(value = "interfaceCode", defaultValue = "") String interfaceCode,
            @RequestParam(value = "condition", defaultValue = "") String condition) {
        if (StringUtils.isBlank(interfaceCode)) {
            throw new ServiceException("参数[interfaceCode]缺失");
        }
        CustomOuterInterface record = customOuterInterfaceService.getRecordByCode(interfaceCode);
        if (record != null && StringUtils.isNotBlank(record.getDetailSql())) {
            List<Map<String, Object>> resultList = customOuterInterfaceService.execute(condition,
                    record.getDetailSql(),record.getName());
            return new RestServiceResult<>(resultList);
        } else {
            throw new ServiceException("获取接口配置数据异常,请检查接口配置,id===》[" + interfaceCode + "]");
        }

    }

    /**
     * 获取所有自主配置数据表
     */
    @IgnoreAuthority
    @RequestMapping("/getTableResource.json")
    public RestServiceResult<List<Map<String, String>>> getTableResource() {
        RestServiceResult<List<Map<String, String>>> result = new RestServiceResult<>();
        try {
            List<Map<String, String>> data = customOuterInterfaceService.getTableResource();
            result.setData(data);
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("待审核数据获取失败");
        }
        return result;

    }

    /**
     * 获取自主配置数据表对应的字段
     */
    @IgnoreAuthority
    @RequestMapping("/getTableColums.json")
    public RestServiceResult<List<Map<String, String>>> getTableColums(String tableId) {
        RestServiceResult<List<Map<String, String>>> result = new RestServiceResult<>();
        try {
            List<Map<String, String>> data = customOuterInterfaceService.getTableColums(tableId);
            result.setData(data);
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("待审核数据获取失败");
        }

        return result;

    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>(2);
        map.put("key1", "value1");
        map.put("key2", "value2");
        List<Map<String, String>> list = new ArrayList<>();
        list.add(map);
        System.err.println(list);
    }
}
